package ui.swing.graphics;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;

import javax.swing.JApplet;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import ui.swing.Console;

public class SineWave extends JApplet {

	private SineDraw sines = new SineDraw();

	private JSlider adjustCycles = new JSlider(1, 30, 5);

	@Override
	public void init() {
		Container cp = getContentPane();
		cp.add(sines);
		adjustCycles.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				sines.setCycles(((JSlider) e.getSource()).getValue());
			}
		});
		cp.add(BorderLayout.SOUTH, adjustCycles);
	}

	public static void main(String[] args) {
		Console.run(new SineWave(), 700, 400);
	}

}

class SineDraw extends JPanel {

	private static final int SCALE_FACTOR = 200;

	private int cycles; // 所希望的完整的正弦波个数

	private int points; // 将要绘制的点的总数

	private double[] sines; // 正弦函数的值

	private int[] pts; // 将要绘制在JPanel上点的y坐标

	public SineDraw() {
		setCycles(5);
	}

	public void setCycles(int newCycles) {
		cycles = newCycles;
		points = SCALE_FACTOR * cycles * 2;
		sines = new double[points];

		for (int i = 0; i < points; i++) {
			double radians = (Math.PI / SCALE_FACTOR) * i;
			sines[i] = Math.sin(radians);
		}
		repaint(); // 通过调用repaint()方法，迫使paintComponent()得到调用
	}

	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		int maxWidth = getWidth();
		double hstep = (double) maxWidth / (double) points;
		int maxHeight = getHeight();
		pts = new int[points];
		for (int i = 0; i < points; i++) {
			pts[i] = (int) (sines[i] * maxHeight / 2 * .95 + maxHeight / 2);
		}
		g.setColor(Color.RED);
		for (int i = 1; i < points; i++) {
			int x1 = (int) ((i - 1) * hstep);
			int y1 = pts[i - 1];
			int x2 = (int) ((i) * hstep);
			int y2 = pts[i];
			g.drawLine(x1, y1, x2, y2);
		}
	}
}
